<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { h, ref } from 'vue';
import { useAuth } from '@/hooks/business/auth';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import type { XxlJobGroup } from '@/service/api';
import { deleteXxlJobGroup, fetchXxlJobGroupList } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { DICT_TYPE, getDictObj } from '@/utils/dict';
import { useBoolean } from '~/packages/hooks/src';
import OnlineAddressModel from './modules/online-address-model.vue';
import XxlJobGroupSearch from './modules/job-group-search.vue';
import XxlJobGroupOperateModel from './modules/job-group-operate-model.vue';

const appStore = useAppStore();
const { hasAuth } = useAuth();
const { bool: onlineAddressModelVisible, setTrue: openOnlineAddressModel } = useBoolean();

const {
  columns,
  columnChecks,
  data,
  loading,
  mobilePagination,
  getData,
  getDataByPage,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchXxlJobGroupList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    appname: null,
    title: null
  },
  columns: () => [
    {
      key: 'appname',
      title: $t('page.base.xxl.executor.appname'),
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'title',
      title: $t('page.base.xxl.executor.executorTitle'),
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'addressType',
      title: $t('page.base.xxl.executor.addressType'),
      align: 'center',
      render: row => {
        if (row.addressType === null) {
          return null;
        }

        const dictObj = getDictObj(DICT_TYPE.EXECUTOR_REGISTER_TYPE, row.addressType);

        return <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>;
      }
    },
    {
      key: 'registryList',
      title: $t('page.base.xxl.executor.addressList'),
      align: 'center',
      render: row => {
        if (row.registryList !== null && row.registryList.length > 0) {
          return h(
            NButton,
            {
              dashed: true,
              type: 'info',
              size: 'small',
              onClick: () => handleOnlineAddress(row)
            },
            {
              default: () => `${$t('page.base.xxl.executor.check')} ( ${row.registryList.length} )`
            }
          );
        }
        return h(
          NButton,
          {
            dashed: true,
            size: 'small'
          },
          {
            default: () => `${$t('common.noData')} ( 0 )`
          }
        );
      }
    },
    {
      key: 'status',
      title: $t('page.base.xxl.executor.status'),
      align: 'center',
      render: row => {
        if (row.status === 1) {
          return h(
            NTag,
            {
              type: 'success',
              bordered: false
            },
            {
              default: () => $t('page.base.xxl.executor.statusAllNormal'),
              icon: () => h(SvgIcon, { icon: 'ant-design:check-circle-twotone' })
            }
          );
        } else if (row.status === 2) {
          return h(
            NTag,
            {
              type: 'error',
              bordered: false
            },
            {
              default: () => $t('page.base.xxl.executor.statusAllException'),
              icon: () => h(SvgIcon, { icon: 'ant-design:exclamation-circle-twotone' })
            }
          );
        }
        return h(
          NTag,
          {
            type: 'warning',
            bordered: false
          },
          {
            default: () => $t('page.base.xxl.executor.statusPartialAnomaly'),
            icon: () => h(SvgIcon, { icon: 'ant-design:stop-twotone' })
          }
        );
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 180,
      render: row => (
        <div class="flex-center gap-8px">
          <div v-show={hasAuth('system:job-group:update')}>
            <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
              {{
                default: () => $t('common.edit'),
                icon: () => h(SvgIcon, { icon: 'ep:edit' })
              }}
            </NButton>
          </div>
          <div v-show={hasAuth('system:job-group:delete')}>
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton type="error" ghost size="small">
                    {{
                      default: () => $t('common.delete'),
                      icon: () => h(SvgIcon, { icon: 'ep:delete' })
                    }}
                  </NButton>
                )
              }}
            </NPopconfirm>
          </div>
        </div>
      )
    }
  ]
});

const { modelVisible, handleAdd, handleEdit, onDeleted, checkedRowKeys, editingData, operateType } = useTableOperate(
  data,
  getData
);

async function handleDelete(id: number) {
  // request
  const { error } = await deleteXxlJobGroup(id);

  await onDeleted(error);
}

function edit(id: number) {
  handleEdit(id);
}

const executorId = ref<number>(0);
function handleOnlineAddress(row: XxlJobGroup) {
  executorId.value = row.id;
  openOnlineAddressModel();
}
</script>

<template>
  <div class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <XxlJobGroupSearch
      v-if="hasAuth('system:job-group:query')"
      v-model:model="searchParams"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />

    <NCard
      :title="$t('page.base.xxl.executor.title')"
      :bordered="false"
      size="small"
      class="sm:flex-1-hidden card-wrapper"
    >
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          create-auth="system:job-group:create"
          delete-auth="system:job-group:delete"
          delete-show="false"
          @add="handleAdd"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1688"
        :loading="loading"
        :row-key="row => row.id"
        remote
        :pagination="mobilePagination"
        class="sm:h-full"
      />

      <XxlJobGroupOperateModel
        v-model:visible="modelVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
      <OnlineAddressModel v-model:visible="onlineAddressModelVisible" :executor-id="executorId" />
    </NCard>
  </div>
</template>

<style scoped></style>
